<template>
  <div class="comments-container" :class="{ 'light-theme': themeStore.isLight }">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>评论管理</span>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索评论内容或用户名"
              prefix-icon="Search"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 评论列表 -->
      <el-table
        :data="commentList"
        style="width: 100%"
        v-loading="loading"
        border
        :fit="true"
        class="comment-table"
        row-class-name="table-row"
        :cell-class-name="tableCellClassName"
        size="small"
      >
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="250">
          <template #default="scope">
            <el-tooltip :content="scope.row.content" placement="top" :show-after="1000">
              <span class="truncate-text">{{ scope.row.content }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="postTitle" label="帖子ID" width="200">
          <template #default="scope">
            <el-tooltip :content="scope.row.postTitle" placement="top" :show-after="1000">
              <span class="truncate-text">{{ scope.row.postTitle }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="评论用户" width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar :size="20" :src="scope.row.avatar || ''" class="author-avatar" />
              <span class="author-name">{{ scope.row.author }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评论时间" width="150">
          <template #default="scope">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ scope.row.createTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <div class="status-container">
              <el-tag :type="getStatusType(scope.row.status)" class="status-tag">
                {{ scope.row.status }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <div class="action-btn-group">
              <el-button type="primary" size="small" @click="viewCommentDetail(scope.row)" text>
                详情
              </el-button>
              <el-button v-if="scope.row.status === '待审核'" type="warning" size="small" @click="auditComment(scope.row)" text>
                审核
              </el-button>
              <el-popconfirm
                title="确定要删除这条评论吗?"
                @confirm="deleteComment(scope.row)"
              >
                <template #reference>
                  <el-button type="danger" size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评论详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="评论详情" width="550px">
      <div v-if="currentComment" class="comment-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="评论ID">{{ currentComment.id }}</el-descriptions-item>
          <el-descriptions-item label="评论内容">{{ currentComment.content }}</el-descriptions-item>
          <el-descriptions-item label="评论用户">
            <div class="detail-author-info">
              <el-avatar :size="30" :src="currentComment.avatar || ''" class="detail-author-avatar" />
              <span>{{ currentComment.author }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="帖子ID">
            <span>{{ currentComment.postId }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="评论时间">{{ currentComment.createTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentComment.status)">{{ currentComment.status }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false" text>关闭</el-button>
          <el-button v-if="currentComment && currentComment.status === '待审核'" type="primary" @click="auditComment(currentComment); detailDialogVisible = false" text>审核</el-button>
          <el-popconfirm
            title="确定要删除这条评论吗?"
            @confirm="deleteComment(currentComment); detailDialogVisible = false"
          >
            <template #reference>
              <el-button type="danger" text>删除评论</el-button>
            </template>
          </el-popconfirm>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="评论审核" width="500px">
      <div v-if="currentComment" class="audit-detail">
        <div v-loading="auditLoading" class="audit-content">
          <div v-if="auditLoading" class="loading-text">正在获取审核结果...</div>
          
          <!-- 审核结果展示 -->
          <div v-if="auditResult && !auditLoading" class="audit-result">
            <el-alert
              :title="auditResult.passed ? '系统审核通过' : '系统审核不通过'"
              :type="auditResult.passed ? 'success' : 'warning'"
              :description="auditResult.message"
              show-icon
              :closable="false"
              class="audit-alert"
            />
            
            <el-descriptions :column="1" border size="small" class="audit-info">
              <el-descriptions-item label="评论ID">{{ auditResult.comment_id }}</el-descriptions-item>
              <el-descriptions-item label="系统建议">
                <el-tag :type="auditResult.passed ? 'success' : 'danger'">
                  {{ auditResult.passed ? '通过' : '封禁' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item v-if="auditResult.label" label="分类标签">{{ auditResult.label }}</el-descriptions-item>
              <el-descriptions-item label="审核状态码">{{ auditResult.status }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="comment-preview">
              <h4>评论内容预览：</h4>
              <div class="preview-header">
                <el-avatar :size="24" :src="currentComment.avatar || ''" class="preview-avatar" />
                <span class="preview-author">{{ currentComment.author }}</span>
                <span class="preview-time">{{ currentComment.createTime }}</span>
              </div>
              <div class="preview-content">{{ currentComment.content }}</div>
            </div>
          </div>
          
          <!-- 审核失败展示 -->
          <div v-if="auditError && !auditLoading" class="audit-error">
            <el-alert
              title="获取审核信息失败"
              type="error"
              :description="auditError"
              show-icon
              :closable="false"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false" text>取消</el-button>
          <el-button 
            type="success" 
            @click="approveComment(currentComment)"
            :disabled="auditLoading || !currentComment"
            text
          >
            通过
          </el-button>
          <el-button 
            type="danger" 
            @click="rejectComment(currentComment)"
            :disabled="auditLoading || !currentComment"
            text
          >
            封禁
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useThemeStore } from '@/stores/theme'
import { Clock } from '@element-plus/icons-vue'


const themeStore = useThemeStore()

// 表格数据
const loading = ref(false)
const commentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

// 详情对话框数据
const detailDialogVisible = ref(false)
const currentComment = ref(null)

// 审核对话框数据
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditResult = ref(null)
const auditError = ref('')

// 设置表格单元格class
const tableCellClassName = () => {
  return 'compact-cell'
}

// 查看评论详情
const viewCommentDetail = (comment) => {
  currentComment.value = comment
  detailDialogVisible.value = true
}

// 审核评论
const auditComment = async (comment) => {
  currentComment.value = comment
  auditDialogVisible.value = true
  auditResult.value = null
  auditError.value = ''
  auditLoading.value = true
  
  try {
    // 调用审核API获取审核结果
    const res = await request.post(`/comment/${comment.id}/audit`)
    
    if (res.data.code === 0) {
      auditResult.value = res.data.data
    } else {
      auditError.value = res.data.msg || '未知错误'
    }
  } catch (error) {
    console.error('获取审核信息失败:', error)
    auditError.value = '获取审核信息失败，请稍后重试'
  } finally {
    auditLoading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '待审核':
      return 'warning'
    case '已驳回':
      return 'danger'
    default:
      return 'info'
  }
}

// 加载评论列表
const loadCommentList = async () => {
  loading.value = true
  try {
    const res = await request.get('/comment/list', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchKeyword.value
      }
    })
    
    // 转换后端返回的数据结构为前端需要的格式
    commentList.value = res.data.data.list.map(item => {
      // 将状态码转换为文字状态
      let statusText = '未知';
      switch(item.status) {
        case 0: statusText = '待审核'; break;
        case 1: statusText = '已通过'; break;
        case 2: statusText = '已驳回'; break;
      }
      
      return {
        id: item.id,
        postId: item.post_id,
        content: item.content,
        postTitle: item.post_id, // 直接使用帖子ID作为显示
        author: item.user?.nickname || `用户${item.user?.id || ''}`,
        avatar: item.user?.avatar || '',
        createTime: new Date(item.create_time).toLocaleString('zh-CN'),
        status: statusText
      }
    })
    total.value = res.data.data.total
  } catch (error) {
    console.error('加载评论列表失败:', error)
    ElMessage.error('加载评论列表失败')
  } finally {
    loading.value = false
  }
}

// 首次加载
onMounted(() => {
  loadCommentList()
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadCommentList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadCommentList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadCommentList()
}

// 审核通过评论
const approveComment = async (comment) => {
  if (!comment) return
  try {
    await request.post(`/comment/status`, {
      id: comment.id,
      status: 1 // 1表示通过
    })
    ElMessage.success('审核通过成功')
    auditDialogVisible.value = false
    loadCommentList()
  } catch (error) {
    console.error('审核通过失败:', error)
    ElMessage.error('审核通过失败')
  }
}

// 驳回评论
const rejectComment = async (comment) => {
  if (!comment) return
  try {
    await request.post(`/comment/status`, {
      id: comment.id,
      status: 2 // 2表示封禁
    })
    ElMessage.success('评论已封禁')
    auditDialogVisible.value = false
    loadCommentList()
  } catch (error) {
    console.error('封禁失败:', error)
    ElMessage.error('封禁失败')
  }
}

// 删除评论
const deleteComment = async (comment) => {
  if (!comment) return
  try {
    await request.delete(`/comment/delete/${comment.id}`)
    ElMessage.success('删除成功')
    loadCommentList()
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败')
  }
}
</script>

<style scoped>
.comments-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-box .el-input {
  width: 220px;
}

/* 表格样式优化 */
.comment-table {
  margin-top: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
  font-size: 12px;
}

.comment-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 4px 0;
  font-size: 12px;
  height: 28px;
  text-align: center;
}

.comment-table :deep(td) {
  padding: 3px 2px;
  vertical-align: middle;
  font-size: 12px;
  height: auto;
}

.compact-cell {
  padding: 0 !important;
}

.comment-table :deep(.el-table__header) {
  border-bottom: 1px solid #ebeef5;
}

.table-row {
  height: auto !important;
}

.table-row:hover {
  background-color: #f9fafc !important;
}

.comment-table :deep(.el-table__row) {
  transition: all 0.3s;
  height: auto !important;
}

.comment-table :deep(.cell) {
  padding-left: 5px;
  padding-right: 5px;
  line-height: 1.2;
}

.action-btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
  justify-content: center;
  padding: 2px;
}

.comment-table :deep(.el-button--small) {
  padding: 1px 5px;
  font-size: 11px;
  min-height: 20px;
  height: 20px;
  line-height: 1;
}

.comment-table :deep(.el-button) {
  margin: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container :deep(.el-pagination) {
  padding: 5px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.truncate-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  max-width: 250px;
  font-size: 12px;
}

.post-title {
  color: #333;
  font-size: 12px;
}

.comment-detail {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.audit-detail {
  padding: 10px 0;
}

.audit-content {
  min-height: 250px;
  display: flex;
  flex-direction: column;
}

.loading-text {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.audit-alert {
  margin-bottom: 20px;
}

.audit-info {
  margin: 15px 0;
}

.comment-preview {
  margin-top: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
}

.preview-avatar {
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.preview-author {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
}

.preview-time {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

.comment-preview h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.preview-content {
  color: #303133;
  line-height: 1.5;
  word-break: break-word;
}

.audit-error {
  margin-top: 20px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 0;
}

.author-avatar {
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  width: 20px !important;
  height: 20px !important;
}

.author-name {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 2px;
  color: #606266;
  font-size: 12px;
}

.time-cell :deep(.el-icon) {
  font-size: 11px;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  text-align: center;
}

.status-tag {
  padding: 2px 6px;
  font-size: 11px;
  border-radius: 2px;
}

/* 暗色主题下样式 */
.comments-container:not(.light-theme) .box-card {
  background: #23262F !important;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(80, 80, 120, 0.18);
  border: 1px solid #23262F;
}

.comments-container:not(.light-theme) .comment-table :deep(th) {
  background-color: #2c3039;
  color: #e0e0e0;
  font-weight: 600;
  border-color: #363b48;
}

.comments-container:not(.light-theme) .comment-table :deep(td) {
  background-color: #23262F;
  color: #bfcbd9;
  border-color: #363b48;
}

.comments-container:not(.light-theme) .table-row:hover {
  background-color: #292c36 !important;
}

.comments-container:not(.light-theme) .comment-table :deep(.el-table__empty-block) {
  background: #23262F;
}

.comments-container:not(.light-theme) .comment-table :deep(.el-table .cell) {
  color: #bfcbd9;
}

.comments-container:not(.light-theme) .comment-table :deep(.el-table__empty-text) {
  color: #7b8190;
  font-size: 1.1rem;
}

.comments-container:not(.light-theme) .card-header > span {
  color: #fff;
  font-weight: 700;
  letter-spacing: 1px;
}

.comments-container:not(.light-theme) .comment-preview {
  background-color: #2a2d38;
}

.comments-container:not(.light-theme) .preview-content {
  color: #e0e0e0;
}

.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination) {
  background-color: #23262F;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}

.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination .el-pagination__total) {
  color: #e0e0e0;
}

.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination .btn-prev),
.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination .btn-next) {
  background-color: #2c3039;
  color: #e0e0e0;
}

.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination .el-pager li) {
  background-color: #2c3039;
  color: #e0e0e0;
}

.comments-container:not(.light-theme) .pagination-container :deep(.el-pagination .el-pager li.active) {
  color: #409EFF;
}

.detail-author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-author-avatar {
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 暗色主题下的评论预览样式 */
.comments-container:not(.light-theme) .preview-header {
  border-bottom-color: #363b48;
}

.comments-container:not(.light-theme) .preview-author {
  color: #e0e0e0;
}

.comments-container:not(.light-theme) .detail-author-info span {
  color: #e0e0e0;
}
</style> 